package com.foxzzz.datamemory.service;

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Function;

@Service
public class TcpForwardService {

    private final static Map<String, Runnable> functionMap = new HashMap<>();
    private final static Map<String, Session> sessionMap = new HashMap<>();

    //每天晚上两点重启Spring
    @Scheduled(cron = "0 0 2 * * ?")
    public void sc() {
        functionMap.forEach((k, v) -> {
            v.run();
        });
    }

    public void restart(String key) {
        Optional.of(functionMap.get(key)).ifPresent(Runnable::run);
    }

    public String forward(String sshUser, String sshHost, Integer sshPort, String sshPassword, Integer lPort, String localHost, Integer rPort) {
        String key = sshHost + ":" + rPort;
        Runnable function = () -> {
            JSch jsch = new JSch();
            try {
                Session session1 = sessionMap.get(key);
                if (session1 != null) {
                    session1.disconnect();
                }
                Session session = jsch.getSession(sshUser, sshHost, sshPort);
                session.setPassword(sshPassword);
                session.setConfig("StrictHostKeyChecking", "no");
                session.connect();
                session.setPortForwardingR(rPort, localHost, lPort);
                sessionMap.put(key, session);
            } catch (Exception e) {
                e.printStackTrace();
            }
        };
        function.run();
        functionMap.put(key, function);
        return key;
    }


    public static void main(String[] args) throws Exception {
        new TcpForwardService().forward("root", "39.96.59.194", 22, "root$#@!", 9876, "localhost", 80);
        Thread.sleep(1000000);
    }
}
